package vben.core.module.gen.org;

import cn.hutool.core.util.StrUtil;
import vben.core.common.mvc.api.R;
import vben.core.common.mvc.dao.JdbcDao;
import vben.core.common.mvc.dao.Sqler;
import vben.core.common.mvc.pojo.ZidName;
import vben.core.common.utils.db.DbType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("gen/org/main")
public class GenOrgMainApi {

    //根据部门ID，查询下级所有的部门,岗位,用户
    @GetMapping()
    public R get(String depid, Integer type, String name) {
        List<ZidName> mapList = new ArrayList<>();
        if (StrUtil.isBlank(name) && StrUtil.isBlank(depid)) {
            return R.ok(mapList);
        }
        if ((type & 2) != 0) {//部门
            Sqler deptSqler = new Sqler("sys_org_dept");
            if (StrUtil.isNotBlank(name)) {
                deptSqler.addLike("t.name", name);
            } else {
                deptSqler.addEqual("t.pid", depid);
            }
            mapList.addAll(jdbcDao.findIdNameList(deptSqler));
        }
        if ((type & 4) != 0) {//岗位
            Sqler postSqler = new Sqler("sys_org_post");
            if (StrUtil.isNotBlank(name)) {
                postSqler.addLike("t.name", name);
            } else {
                postSqler.addEqual("t.depid", depid);
            }
            mapList.addAll(jdbcDao.findIdNameList(postSqler));
        }
        if ((type & 8) != 0) {//用户
            Sqler userSqler = new Sqler("sys_org_user");
            if (StrUtil.isNotBlank(name)) {
                userSqler.addLike("t.name", name);
            } else {
                userSqler.addEqual("t.depid", depid);
            }
            mapList.addAll(jdbcDao.findIdNameList(userSqler));
        }
        return R.ok(mapList);
    }

    //根据组织架构ids获取SysOrg对象数组
    @GetMapping("list")
    public R getOrgList(String ids) {
        Sqler sqler = new Sqler("sys_org");
        if (ids.contains(";")) {
//            ids = "('" + ids.replaceAll(";", "','") + "')";
//            sqler.addWhere("id in " + ids);
            ids = "'" + ids.replaceAll(";", "','") + "'";
            sqler.addWhere("id in " +"("+ ids+")");
            if (DbType.MYSQL.equals(jdbcDao.getDbType())) {
                sqler.addOrder("field(id," + ids + ")");
            }else if(DbType.ORACLE.equals(jdbcDao.getDbType())){
                sqler.addOrder("INSTR('"+ids.replaceAll("'","")+"',id)");
            }else if(DbType.SQL_SERVER.equals(jdbcDao.getDbType())){
                sqler.addOrder("CHARINDEX(id,'"+ids.replaceAll("'","")+"')");
            }
        }else{
            sqler.addEqual("id",ids);
        }
        return R.ok(jdbcDao.findIdNameList(sqler));
    }

    @Autowired
    private JdbcDao jdbcDao;


}
